﻿using System;
/*1、为示例中的泛型链表类添加类似于List<T> 类的ForEach(Action<T> action)方法。
    通过调用这个方法打印链表元素，求最大值、最小值和求和（使用lambda表达式实现）。*/
public class Node<T>
{
    public Node<T> Next { get; set; }
    public T Data { get; set; }
    public Node(T t)
    {
        Next = null;
        Data = t;
    }
}
public class GenericList<T>
{
    private Node<T> head;
    private Node<T> tail;
    public GenericList()
    {
        head = tail = null;
    }
    public Node<T> Head
    {
        get => head;
    }
    public void Add(T t)
    {
        Node<T> n = new Node<T>(t);
        if (tail == null)
        {
            head = tail = n;
        }
        else
        {
            tail.Next = n;
            tail = n;
        }
    }
    public void ForEach(Action<T> action)
    {
        if(action == null)
        {
            throw new ArgumentNullException();
        }
        Node<T> temp = head;
        while (temp != null)
        {
            action(temp.Data);
            temp = temp.Next;
        }
    }
    public int getMax()
        {
        int max = 0;
        ForEach(x =>
        {
            if (Convert.ToInt32(x) > max)
            {
                max = Convert.ToInt32(x);
            }
        });
        return max;
    }
    public int getMin()
    {
        int min = 0;
        ForEach(x =>
        {
            if (Convert.ToInt32(x) < min)
            {
                min = Convert.ToInt32(x);
            }
        });
        return min;
    }
    public int getSum()
    {
        int sum = 0;
        ForEach(x =>
        {
            sum += Convert.ToInt32(x);
        });
        return sum;
    }
}
class Program
{
    static void Main(string[] args)
    {
        GenericList<int> inlist = new GenericList<int>();
        Console.WriteLine("Input 10 numbers into List:");
        for (int i = 0; i < 10; i++)
        {
            Random random = new Random();
            inlist.Add(random.Next(100));
        }
        for(Node<int> node = inlist.Head; node != null; node = node.Next)
        {
            Console.WriteLine(node.Data);
        }
        Console.WriteLine("Max: " + inlist.getMax());
        Console.WriteLine("Min: " + inlist.getMin());
        Console.WriteLine("Sum: " + inlist.getSum());
    }
}